//
//  PhotoSelectViewController.m
//  WuliHanhan
//
//  Created by chen tang on 16/3/3.
//  Copyright © 2016年 LVpeng. All rights reserved.
//

#import "PhotoSelectViewController.h"
#import "Header.h"
#import "PhotoImageModel.h"
#import "DataBaseSaveEditeImageModel.h"



#import "PhotoCollectionViewCell.h"
#import "MyLayout.h"
#import "ImagePushButton.h"


#import <PhotosUI/PhotosUI.h>



//#import "CreatImageWithTextViewController.h"
#import "CreatEditeViewController.h"

@interface PhotoSelectViewController ()<UICollectionViewDataSource, UICollectionViewDelegateFlowLayout,
                                                                                                        PhotoCollectionViewCellDelegate,
                                                                                                        ImagePushButtonDelegate>





{
    NSMutableArray *nameIndexArray;
    NSMutableArray *sourceImageArray;
    int WtiteToInt;
    BOOL judgeDis;
    ImagePushButton *imagePushButton;
}

@property (strong, nonatomic)UICollectionView *collectionView;


@property (nonatomic, strong) NSMutableArray *imageArray;


@end

@implementation PhotoSelectViewController



sloganIntence(PhotoSelectViewController);




- (void)loadView
{
    [super loadView];
    
    [self.view setBackgroundColor:[UIColor whiteColor]];
    
    _imageArray = [NSMutableArray new];
    sourceImageArray = [NSMutableArray new];
    nameIndexArray = [NSMutableArray new];
    
    
    [self.navigationController setNavigationBarHidden:YES];
    
    
    UIView *titleView = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, WithView, 44.0)];
    [titleView setBackgroundColor:uicolor(254, 195, 9)];
    [self.view addSubview:titleView];
    
    UILabel *titleLable = [[UILabel alloc] initWithFrame:CGRectMake(0, 12.5, WithView, 20.0)];
    [titleLable setTextAlignment:NSTextAlignmentCenter];
    [self.view addSubview:titleLable];
    [titleLable setText:@"选择照片"];
    [titleLable setTextColor:uicolor(13, 20, 25)];
    
    
    
    
    UICollectionViewFlowLayout *flowLayout=[[UICollectionViewFlowLayout alloc] init];
    [flowLayout setScrollDirection:UICollectionViewScrollDirectionVertical];
    
    
    self.collectionView=[[UICollectionView alloc] initWithFrame:CGRectMake(0, 46, WithView, heightView-104) collectionViewLayout:flowLayout];
    [self.collectionView setBackgroundColor:[UIColor clearColor]];
    
    //注册Cell，必须要有
    [self.collectionView registerClass:[PhotoCollectionViewCell class] forCellWithReuseIdentifier:@"UICollectionViewCell"];
    
    [self.view addSubview:self.collectionView];
    
    
    UIImage *image = nil;
    
    image = [UIImage imageNamed:@"quxiao.png"];
    
    UIButton *calcanButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, image.size.width, image.size.height)];
    [calcanButton setBackgroundImage:image forState:UIControlStateNormal];
    [self.view addSubview:calcanButton];
    [calcanButton addTarget:self action:@selector(cancleToPopView) forControlEvents:UIControlEventTouchUpInside];
    
    

    imagePushButton = [[ImagePushButton alloc] initWithFrame:CGRectMake(0, 0, 64, 26)];
    [imagePushButton setCenter:CGPointMake(WithView-42.0, 22.0)];
    [imagePushButton setMImagePushButtonDelegate:self];
    [self.view addSubview:imagePushButton];
    
    [self addObserVweToCommit];
    
    WtiteToInt = 0;
    
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.collectionView.dataSource=self;
    self.collectionView.delegate=self;
    [self.collectionView setAllowsMultipleSelection:YES];
    
    if (_plusImage)
    {
        
    }
    else
    {
    //第一次进入
        [[DataBaseSaveEditeImageModel sharedInstance] openDataBase];
    }
    
    
    [self changeSelectJudge];
}



- (void)addObserVweToCommit
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(xiangceBeganReolad) name:imageSaveSuccess object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeSelectJudge) name:getXiangceImage object:nil];
}




- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}





- (void)changeSelectJudge
{
    
    [_imageArray removeAllObjects];
    [sourceImageArray removeAllObjects];
    [nameIndexArray removeAllObjects];
    
    
    [[PhotoImageModel sharedInstance] setSelectAtIndenx:0 WithCallBack:^(NSArray *array, NSArray *imageOrnArray){
        [_imageArray addObjectsFromArray:array];
        
        [sourceImageArray addObjectsFromArray:imageOrnArray];
    
    }];

    
    [[DataBaseSaveEditeImageModel sharedInstance] rearDataBaseForPhotos:^(NSArray *nameArray, NSArray *dataArray){
        
        [nameIndexArray addObjectsFromArray:nameArray];
        NSLog(@"%@", nameIndexArray);
        [_collectionView reloadData];
    }];

    
    [imagePushButton setNumberInt:(int)[nameIndexArray count]];
}




//拍照保存成功刷新相册
- (void)xiangceBeganReolad
{
    [_imageArray removeAllObjects];
    [sourceImageArray removeAllObjects];
    [nameIndexArray removeAllObjects];
    
    
    [[DataBaseSaveEditeImageModel sharedInstance] updateDataBaseWithIndex];
    
    [[PhotoImageModel sharedInstance] setSelectAtIndenx:0 WithCallBack:^(NSArray *array, NSArray *imageOrnArray){
        [_imageArray addObjectsFromArray:array];
        
        [sourceImageArray addObjectsFromArray:imageOrnArray];
        
        
    }];

    
    [[DataBaseSaveEditeImageModel sharedInstance] rearDataBaseForPhotos:^(NSArray *nameArray, NSArray *dataArray){
        
        [nameIndexArray addObjectsFromArray:nameArray];
        [_collectionView reloadData];
    }];

}




//取消选择
- (void)cancleToPopView
{
    [self dismissViewControllerAnimated:YES completion:nil];
    [[UIApplication sharedApplication] setStatusBarHidden:NO];
}


//进入创作
- (void)pushToCreatView
{
    if (_plusImage)
    {
        [self dismissViewControllerAnimated:YES completion:nil];
        
    }
    else
    {
        CreatEditeViewController *creatImageVC = [[CreatEditeViewController alloc] init];
        [self.navigationController pushViewController:creatImageVC animated:YES];
    }
    

    
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return [_imageArray count];
}


//每个UICollectionView展示的内容
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString * CellIdentifier = @"UICollectionViewCell";
    PhotoCollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:CellIdentifier forIndexPath:indexPath];
    [cell setTag:indexPath.row];
//    [cell.dataImage setImage:_imageArray[indexPath.row]];
    cell.dataImage = _imageArray[indexPath.row];
    [cell setMPhotoCollectionViewCellDelegate:self];
    [cell setModelWith:nameIndexArray];
    
    return cell;
}
#pragma mark --UICollectionViewDelegateFlowLayout

//定义每个Item 的大小

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake(biliwith(77.0), biliwith(77.0));
}

//定义每个UICollectionView 的 margin
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(0, 0, 0, 0);
}



- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    
    return 4.0;
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    return 4.0;
}



//cell代理
- (void)chooseImageWithIndex:(NSInteger)index withSelectBool:(BOOL)select
{
    
    if (select)
    {
//        NSLog(@"xuanzhong");
        [[PhotoImageModel sharedInstance] selectAsset:sourceImageArray[index] getOrnImage:^(NSData *data){
            
            [[DataBaseSaveEditeImageModel sharedInstance] insertImage:data withIndex:[NSString stringWithFormat:@"%d", (int)index]];      //注意打开数据库
            [nameIndexArray addObject:[NSString stringWithFormat:@"%d", (int)index]];
        }];

        [imagePushButton setNumberInt:(int)[nameIndexArray count]];
    }
    else
    {
//        NSLog(@"mei");
        [nameIndexArray removeObject:[NSString stringWithFormat:@"%d", (int)index]];
        [imagePushButton setNumberInt:(int)[nameIndexArray count]];
        [[DataBaseSaveEditeImageModel sharedInstance] deletaIMage:[NSString stringWithFormat:@"%d", (int)index]];
    }
    
    
}



/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
